<template>
  <div class="questionnaires-page">
    <div class="content-wrapper">
      <h1 class="page-title">问卷调查</h1>
      
      <!-- 问卷列表 -->
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in questionnaires" :key="item.id">
          <el-card class="questionnaire-card" shadow="hover">
            <h3 class="title">{{ item.title }}</h3>
            <p class="description">{{ item.description || '暂无描述' }}</p>
            <div class="card-footer">
              <div class="meta">
                <el-tag :type="getStatusType(item.status)">{{ getStatusText(item.status) }}</el-tag>
                <span class="time">{{ formatDate(item.createTime) }}</span>
              </div>
              <!-- 根据问卷状态和提交状态显示不同的按钮 -->
              <template v-if="item.status === 1">
                <el-button 
                  :type="questionnaireStore.isSubmitted(item.id) ? 'success' : 'primary'"
                  @click="handleFill(item)"
                >
                  {{ getButtonText(item) }}
                </el-button>
              </template>
              <template v-else-if="item.status === 2 && questionnaireStore.isSubmitted(item.id)">
                <el-button 
                  type="success"
                  @click="handleFill(item)"
                >
                  查看提交
                </el-button>
              </template>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[9, 18, 36]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 提交记录对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="提交记录"
        width="50%"
      >
        <div v-if="currentQuestionnaire" class="submission-details">
          <h3>{{ currentQuestionnaire.title }}</h3>
          <div class="description" v-if="currentQuestionnaire.description">
            {{ currentQuestionnaire.description }}
          </div>
          <div v-for="(question, qIndex) in currentQuestionnaire.questions" :key="qIndex" class="answer-item">
            <div class="question">
              <span class="question-number">{{ qIndex + 1 }}. </span>
              {{ question.title }}
              <span v-if="question.required" class="required">*</span>
            </div>
            <div class="answer">
              <template v-if="question.type === 1"> <!-- 单选题 -->
                <el-tag v-if="getAnswer(question.id) !== null" class="answer-tag">
                  {{ getOptionLabel(question, getAnswer(question.id)) }}
                </el-tag>
                <el-tag v-else type="info">未作答</el-tag>
              </template>
              <template v-else-if="question.type === 2"> <!-- 多选题 -->
                <template v-if="getAnswer(question.id)?.length">
                  <el-tag 
                    v-for="(optionId, index) in getAnswer(question.id)"
                    :key="index"
                    class="answer-tag"
                  >
                    {{ getOptionLabel(question, optionId) }}
                  </el-tag>
                </template>
                <el-tag v-else type="info">未作答</el-tag>
              </template>
              <template v-else-if="question.type === 3"> <!-- 填空题 -->
                <div class="text-answer">
                  {{ getAnswer(question.id) || '未作答' }}
                </div>
              </template>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { useQuestionnaireStore } from '@/stores/questionnaire'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { getSubmission } from '@/api/questionnaire'

const router = useRouter()
const questionnaireStore = useQuestionnaireStore()
const userStore = useUserStore()
const questionnaires = ref([])
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const dialogVisible = ref(false)
const currentQuestionnaire = ref(null)
const currentAnswers = ref(null)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '未发布'
    case 1: return '进行中'
    case 2: return '已结束'
    default: return '未知'
  }
}

const getButtonText = (questionnaire) => {
  if (questionnaire.status === 1) {
    if (questionnaireStore.isSubmitted(questionnaire.id)) {
      return '查看提交'
    }
    return '立即填写'
  }
  return ''
}

const loadQuestionnaires = async () => {
  try {
    const res = await request.get('/api/questionnaire/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.code === 200) {
      questionnaires.value = res.data.records.sort((a, b) => {
        return new Date(b.createTime) - new Date(a.createTime)
      })
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载问卷列表失败:', error)
  }
}

const handleFill = async (questionnaire) => {
  if (questionnaireStore.isSubmitted(questionnaire.id)) {
    await showSubmission(questionnaire.id)
  } else {
    if (questionnaire.status === 2) {
      return
    }
    
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push({
        path: '/login',
        query: { redirect: `/front/questionnaires/${questionnaire.id}/fill` }
      })
      return
    }
    router.push(`/front/questionnaires/${questionnaire.id}/fill`)
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadQuestionnaires()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadQuestionnaires()
}

const parsedAnswers = computed(() => {
  if (!currentAnswers.value) return []
  try {
    // 解析答案
    const answersObj = JSON.parse(currentAnswers.value)
    // 处理不同的答案格式
    let normalizedAnswers = answersObj
    if (answersObj.answers) {
      normalizedAnswers = answersObj.answers
    }
    // 获取问卷中的问题
    const questions = currentQuestionnaire.value.questions || []
    
    return questions.map(question => {
      const answer = normalizedAnswers[question.id]
      if (!answer) return {
        question: question.title,
        answer: ['未作答']
      }
      return {
        question: question.title,
        answer: Array.isArray(answer) ? answer : answer ? [answer] : ['未作答']
      }
    })
  } catch (e) {
    console.error('解析答案失败:', e, currentAnswers.value)
    return []
  }
})

// 获取答案
const getAnswer = (questionId) => {
  if (!currentAnswers.value) return null
  try {
    let answers = currentAnswers.value
    // 如果是字符串，尝试解析
    if (typeof answers === 'string') {
      answers = JSON.parse(answers)
    }
    
    // 检查是否有 answers 属性
    if (answers.answers) {
      answers = answers.answers
    }
    
    // 获取特定问题的答案
    let answer = answers[questionId]
    if (!answer) {
      // 尝试使用 'q' + questionId 的格式
      answer = answers[`q${questionId}`]
    }
    
    if (answer === undefined || answer === null) {
      return null
    }
    
    // 如果是数组，直接返回
    if (Array.isArray(answer)) {
      return answer
    }
    
    // 如果是字符串（填空题答案），直接返回
    if (typeof answer === 'string') {
      return answer
    }
    
    // 如果是数字（单选题答案），返回数组形式
    if (typeof answer === 'number') {
      return answer
    }
    
    return null
  } catch (e) {
    console.error('获取答案失败:', e, currentAnswers.value)
    return null
  }
}

// 获取选项标签
const getOptionLabel = (question, optionId) => {
  if (question.type === 3) {
    // 如果是填空题，直接返回答案内容
    return optionId
  }
  
  // 对于单选和多选题，查找选项内容
  const option = question.options?.find(opt => opt.id == optionId) // 使用宽松相等
  return option ? option.content : optionId
}

const showSubmission = async (questionnaireId) => {
  try {
    const res = await getSubmission(questionnaireId)
    if (res.code === 200) {
      currentQuestionnaire.value = res.data.questionnaire
      currentAnswers.value = res.data.answers
      console.log('问卷数据:', res.data.questionnaire)
      console.log('答案数据:', res.data.answers)
      console.log('问题列表:', res.data.questionnaire.questions)
      console.log('解析后的答案:', currentAnswers.value)
      dialogVisible.value = true
      return true
    }
    ElMessage.warning('未找到提交记录')
    return false
  } catch (error) {
    console.error('加载提交记录失败:', error)
    ElMessage.error('加载提交记录失败')
    return false
  }
}

onMounted(() => {
  loadQuestionnaires()
  if (userStore.isLoggedIn) {
    questionnaireStore.loadSubmittedQuestionnaires()
  }
})
</script>

<style lang="scss" scoped>
.questionnaires-page {
  .content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .page-title {
    font-size: 28px;
    color: #303133;
    margin-bottom: 30px;
    text-align: center;
  }

  .questionnaire-card {
    height: 100%;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    .title {
      font-size: 18px;
      color: #303133;
      margin: 0 0 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .description {
      flex: 1;
      color: #606266;
      line-height: 1.6;
      margin: 0 0 15px;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .meta {
        display: flex;
        align-items: center;
        gap: 10px;

        .time {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }

  .answers-content {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 20px;

    .description {
      color: #606266;
      font-size: 14px;
      margin-bottom: 20px;
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .answer-item {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .question {
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;
      }

      .answer {
        color: #606266;
        line-height: 1.6;

        .answer-tag {
          margin-right: 8px;
          margin-bottom: 8px;
        }
      }
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .questionnaires-page {
    .content-wrapper {
      padding: 10px;
    }

    .questionnaire-card {
      margin-bottom: 15px;

      .title {
        font-size: 16px;
      }

      .description {
        -webkit-line-clamp: 2;
      }
    }
  }
}

.submission-details {
  .question {
    font-weight: bold;
    margin-bottom: 10px;
    
    .question-number {
      color: #409EFF;
      margin-right: 5px;
    }
    
    .required {
      color: #F56C6C;
      margin-left: 4px;
    }
  }
  
  .answer {
    margin-bottom: 20px;
    padding-left: 20px;
    
    .answer-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
    
    .text-answer {
      color: #606266;
      line-height: 1.6;
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
</style> 